package qingyu.ai.common.speech.recognizer;

import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;

import java.util.List;

public class RecognizerAdapter implements RecognizerListener {
    private RecognizerCallBack callBack;

    private StringBuilder sb;

    public RecognizerAdapter(RecognizerCallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    public void onVolumeChanged(int i, byte[] bytes) {

    }

    @Override
    public void onBeginOfSpeech() {
        sb = new StringBuilder();
    }

    @Override
    public void onEndOfSpeech() {

    }

    @Override
    public void onResult(RecognizerResult recognizerResult, boolean isLast) {
        sb.append(parseData(recognizerResult.getResultString()));
        if (callBack != null && isLast)
            callBack.onRecognizerResult(sb.toString());
    }

    @Override
    public void onError(SpeechError speechError) {
        if (callBack != null)
            callBack.onError(speechError.getErrorCode(), speechError.getErrorDescription());
    }

    @Override
    public void onEvent(int i, int i1, int i2, Bundle bundle) {

    }

    private static String parseData(String resultString) {
        if (!TextUtils.isEmpty(resultString)) {
            Gson gson = new Gson();
            VoiceBean voiceBean = gson.fromJson(resultString, VoiceBean.class);
            List<VoiceBean.WsBean> ws = voiceBean.getWs();

            StringBuffer sb = new StringBuffer();
            for (VoiceBean.WsBean wb : ws) {
                String w = wb.getCw().get(0).getW();
                sb.append(w);
            }
            return sb.toString();
        }
        return "";
    }

}
